@echo off
chcp 65001 > nul
color 0B
setlocal enabledelayedexpansion

:: 设置项目路径变量，提高可维护性
set "PROJECT_ROOT=%CD%"
set "API_PROJECT=%PROJECT_ROOT%\Net8.Project"
set "PUBLISH_DIR=%PROJECT_ROOT%\.PublishFiles"
set "OUTPUT_DIR=%API_PROJECT%\bin\Debug\net8.0"

echo =====================================
echo 开始发布 Net8.Project 项目...
echo =====================================

:: 清理发布目录
echo 清理发布目录...
if exist "%PUBLISH_DIR%" (
    rmdir /S /Q "%PUBLISH_DIR%"
    if errorlevel 1 (
        echo 错误: 无法清理发布目录 %PUBLISH_DIR%
        goto :error
    )
)
mkdir "%PUBLISH_DIR%"
if errorlevel 1 (
    echo 错误: 无法创建发布目录 %PUBLISH_DIR%
    goto :error
)

:: 恢复依赖项
echo 恢复 NuGet 包...
dotnet restore "%API_PROJECT%"
if errorlevel 1 (
    echo 错误: 包恢复失败
    goto :error
)

:: 构建项目
echo 构建项目...
dotnet build "%API_PROJECT%" --configuration Debug --no-restore
if errorlevel 1 (
    echo 错误: 项目构建失败
    goto :error
)

:: 发布项目
echo 发布项目到 %OUTPUT_DIR%...
dotnet publish "%API_PROJECT%" --configuration Debug --output "%OUTPUT_DIR%" --no-build
if errorlevel 1 (
    echo 错误: 项目发布失败
    goto :error
)

:: 复制发布文件
echo 复制发布文件到 %PUBLISH_DIR%...
xcopy /E /I /Y "%OUTPUT_DIR%\*" "%PUBLISH_DIR%\"
if errorlevel 1 (
    echo 错误: 文件复制失败
    goto :error
)

echo =====================================
echo 发布成功!
echo 请查看 .PublishFiles 目录
echo =====================================

pause
exit /b 0

:error
echo =====================================
echo 发布过程中发生错误!
echo =====================================
pause
exit /b 1